import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute} from '@angular/router';
import {Location} from '@angular/common';
import {PlatformService} from '../platform.service';
import {YesOrNo} from '../../../public/setting/enums';

@Component({
  selector: 'app-platform-account-edit',
  templateUrl: './platform-account-edit.component.html',
  styleUrls: ['./platform-account-edit.component.css']
})
export class PlatformAccountEditComponent implements OnInit {
  public isConfirmLoading: boolean = false;
  public code: string; //platformAccount
  public validateForm: FormGroup;//企业登录的表单

  constructor(private fb: FormBuilder, private platformService: PlatformService, private route: ActivatedRoute, public location: Location) {
    this.validateForm = this.fb.group({
      account: [null, Validators.compose([Validators.required])], // 账户
      password: [null, Validators.compose([Validators.required])], // 密码
      isSuper: [false, Validators.compose([Validators.required])], // 是否是超级账户 Y,N
    });
  }

  ngOnInit() {
    this.route.url.subscribe(url => {
      const curPath = url[0].path;
      if (curPath === 'modify') {
        this.code = this.route.snapshot.params.code;//获取参数
        this.loadPlatformAccountInfo();
      }//修改前查询出供应商信息
    });
  }

  /**
   * 表单确认
   */
  addPlatformAccount($event) {
    $event.preventDefault();
    //1.进行脏检查，提示未填的必填字段
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.isConfirmLoading = true;
    let formData = Object.assign({}, this.validateForm.value);
    formData.isSuper = formData.isSuper ? YesOrNo.yes : YesOrNo.no;//将布尔值转换成状态值
    //添加platformAccount
    if (this.code) {
      formData.code = this.code;
      this.platformService.modifyPlatformAccount(formData).then((data: any) => {
        this.isConfirmLoading = false;
        this.validateForm.reset();
        this.location.back();
      }).catch(res => this.isConfirmLoading = false);
    } else {
      this.platformService.addPlatformAccount(formData).then((data: any) => {
        this.isConfirmLoading = false;
        this.location.back();
      }).catch(res => this.isConfirmLoading = false);
    }
  }

  /**
   * 查询platformAccount信息
   */
  loadPlatformAccountInfo() {
    this.platformService.loadPlatformAccountByCode(this.code).then((data: any) => {
      data.isSuper = data.isSuper === YesOrNo.yes;//将状态值转换成布尔值
      this.validateForm.patchValue(data);
    });
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }
}
